package com.Shuang.UDP;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

public class Client {
    public static void main(String[] args){
        try {
            //1 创建要客户端对象
            DatagramSocket socket = new DatagramSocket();

            Scanner sc = new Scanner(System.in);

            while (true) {
                //2 创建要封装的数据包对象
       /*
             public DatagramPacket(byte buf[], int length,
             InetAddress address, int port)
             封装要发的数据，发的数据大小，服务端ip地址（找到服务端主机），服务端端口 找到服务端程序
        */
                System.out.println("请说：");
                String msg = sc.nextLine();

                //客服端发送退出条件
                if (msg.equals("exit")){
                    System.out.println("已退出，欢迎下次使用~");
                    socket.close();  //释放资源
                    break;
                }

                byte[] msgBytes = msg.getBytes();
                DatagramPacket packet = new DatagramPacket(msgBytes, msgBytes.length,
                        InetAddress.getLocalHost(), 6666);
                //3 将数据包发送出去
                socket.send(packet);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
